#!/bin/bash

if [ $# -lt 1 ]; then
    echo "$0 <pid>"
    exit 1
fi

total_old=0
tm=0
tm_old=0
per=0
CLK=$(getconf CLK_TCK)

function usage_pid()
{
    PID=$1

    data=$(awk '{print $14,$15}' /proc/$PID/stat)
    tm=$(date "+%s.%3N")
    user=$(echo $data | awk '{print $1}')
    sys=$(echo $data | awk '{print $2}')

    total=$((user + sys))
    ret=$((total - total_old))
    total_old=$total
    et=$(echo "${tm} - ${tm_old}" | bc)
    tm_old=$tm
    per=$(echo "scale=3; $ret * 100 / ${CLK}  / $et" | bc)
}

function usage_cg()
{
    CG=$1

    user=$(< $CG/cpuacct.usage_user)
    sys=$(< $CG/cpuacct.usage_sys)
    tm=$(date "+%s.%3N")

    total=$((user + sys))
    ret=$((total - total_old))
    total_old=$total
    et=$(echo "${tm} - ${tm_old}" | bc)
    tm_old=$tm
    per=$(echo "scale=3; $ret / $et / 1000000000 * 100" | bc)
}


while true

do
    usage_cg $1
    #usage_pid $1
    echo "cpu usage for $1: $per %"
    sleep 1

done

